package logic

import (
	"context"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"math/rand"
	"novel-kit/model/cache"
	"novel-kit/model/mysql"
	"strconv"

	"novel-kit/novelrpc/internal/svc"
	"novel-kit/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginUserLogic {
	return &LoginUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录注册一体化
func (l *LoginUserLogic) LoginUser(in *novelrpc.LoginUserRequest) (*novelrpc.LoginUserResponse, error) {
	// todo: add your logic here and delete this line
	var User mysql.User
	if err := User.FindUserByMobil(mysql.DB, in.Mobile); err != nil {
		result, _ := cache.Rdb.Get(l.ctx, "sendsms"+in.Mobile).Result()
		if result != in.SmsCode {
			return nil, errors.New("验证码不正确")
		}
		User = mysql.User{
			Model:     gorm.Model{},
			Mobile:    in.Mobile,
			Password:  in.Password,
			HeadImage: "https://cn.bing.com/images/search?q=%e5%ae%a2%e6%9c%8d%e5%a4%b4%e5%83%8f&id=4DF2AD69A975B2562FA016D586E08800D6E0AFC0&FORM=IACFIR",
			NickName:  fmt.Sprintf("用户%d", rand.Intn(90000)+10000),
		}
		if err = User.UserAdd(mysql.DB); err != nil {
			return nil, errors.New("添加错误")
		}

	} else {
		if in.LoginType == "1" {
			if in.Password != User.Password {
				return nil, errors.New("密码错误")
			}
		} else if in.LoginType == "2" {
			result, _ := cache.Rdb.Get(l.ctx, "sendsms"+in.Mobile).Result()
			if result != in.SmsCode {
				return nil, errors.New("验证码不正确")
			}
		} else {
			return nil, errors.New("请选择正确的方式登录")
		}
	}

	return &novelrpc.LoginUserResponse{
		UserId: strconv.Itoa(int(User.ID)),
	}, nil
}
